<template>
  <div class="message-detail">
    <div class="message-header">
      <div class="sender-info">
        <el-avatar
          :size="50"
          :src="message.senderAvatar"
          :icon="message.type === 'system' ? 'Bell' : 'User'"
          :style="{ backgroundColor: message.type === 'system' ? '#f56c6c' : '#409eff' }"
        />
        <div class="sender-details">
          <div class="sender-name">
            {{ message.senderName || '系统通知' }}
            <el-tag
              v-if="message.type === 'system'"
              type="danger"
              size="small"
              class="message-type-tag"
            >
              系统消息
            </el-tag>
          </div>
          <div class="message-time">
            {{ formatTime(message.createTime) }}
          </div>
        </div>
      </div>
      
      <div class="message-status">
        <el-tag
          :type="message.isRead ? 'success' : 'warning'"
          size="small"
        >
          {{ message.isRead ? '已读' : '未读' }}
        </el-tag>
      </div>
    </div>

    <div class="message-title">
      {{ message.title }}
    </div>

    <div class="message-content">
      <div v-if="message.type === 'system'" class="system-content">
        <el-alert
          :title="message.title"
          :description="message.content"
          :type="getSystemMessageType(message.subType)"
          show-icon
          :closable="false"
        />
        
        <!-- 系统消息的额外信息 -->
        <div v-if="message.extraData" class="extra-data">
          <el-descriptions :column="2" border>
            <el-descriptions-item
              v-for="(value, key) in message.extraData"
              :key="key"
              :label="getExtraDataLabel(key)"
            >
              {{ value }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      
      <div v-else class="user-content">
        <div class="content-text" v-html="formatContent(message.content)"></div>
        
        <!-- 附件 -->
        <div v-if="message.attachments && message.attachments.length > 0" class="attachments">
          <h4>附件</h4>
          <div class="attachment-list">
            <div
              v-for="attachment in message.attachments"
              :key="attachment.id"
              class="attachment-item"
            >
              <el-link
                :href="attachment.url"
                :download="attachment.name"
                type="primary"
                :icon="getFileIcon(attachment.type)"
              >
                {{ attachment.name }}
              </el-link>
              <span class="file-size">{{ formatFileSize(attachment.size) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="message-actions">
      <el-button
        v-if="message.type !== 'system'"
        type="primary"
        @click="handleReply"
      >
        回复消息
      </el-button>
      
      <el-button
        v-if="message.type === 'system' && message.actionUrl"
        type="success"
        @click="handleAction"
      >
        {{ message.actionText || '查看详情' }}
      </el-button>
      
      <el-button @click="handleMarkAsRead" v-if="!message.isRead">
        标记为已读
      </el-button>
    </div>

    <!-- 相关消息 -->
    <div v-if="relatedMessages.length > 0" class="related-messages">
      <h4>相关消息</h4>
      <div class="related-list">
        <div
          v-for="related in relatedMessages"
          :key="related.id"
          class="related-item"
          @click="$emit('message-click', related)"
        >
          <div class="related-title">{{ related.title }}</div>
          <div class="related-time">{{ formatTime(related.createTime) }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'

// Props
const props = defineProps({
  message: {
    type: Object,
    required: true
  }
})

// Emits
const emit = defineEmits(['reply', 'mark-read', 'message-click'])

// 响应式数据
const relatedMessages = ref([])

// 计算属性
const formattedContent = computed(() => {
  return formatContent(props.message.content)
})

// 方法
const formatTime = (time) => {
  if (!time) return ''
  
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatContent = (content) => {
  if (!content) return ''
  
  // 简单的文本格式化，将换行符转换为<br>
  return content.replace(/\n/g, '<br>')
}

const getSystemMessageType = (subType) => {
  const typeMap = {
    'info': 'info',
    'warning': 'warning',
    'error': 'error',
    'success': 'success',
    'audit': 'warning',
    'contract': 'info',
    'payment': 'success'
  }
  return typeMap[subType] || 'info'
}

const getExtraDataLabel = (key) => {
  const labelMap = {
    'houseId': '房源ID',
    'contractId': '合同ID',
    'amount': '金额',
    'status': '状态',
    'reason': '原因',
    'operator': '操作人',
    'operateTime': '操作时间'
  }
  return labelMap[key] || key
}

const getFileIcon = (fileType) => {
  const iconMap = {
    'image': 'Picture',
    'document': 'Document',
    'pdf': 'Document',
    'video': 'VideoPlay',
    'audio': 'Headphone'
  }
  return iconMap[fileType] || 'Document'
}

const formatFileSize = (size) => {
  if (!size) return ''
  
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  let fileSize = size
  
  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024
    index++
  }
  
  return `${fileSize.toFixed(1)} ${units[index]}`
}

const handleReply = () => {
  emit('reply', props.message)
}

const handleMarkAsRead = () => {
  emit('mark-read', props.message)
}

const handleAction = () => {
  if (props.message.actionUrl) {
    window.open(props.message.actionUrl, '_blank')
  }
}
</script>

<style scoped>
.message-detail {
  padding: 20px 0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.sender-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.sender-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.sender-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 16px;
  line-height: 1.4;
}

.message-content {
  margin-bottom: 24px;
}

.system-content .extra-data {
  margin-top: 16px;
}

.user-content .content-text {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
  margin-bottom: 16px;
}

.attachments {
  margin-top: 16px;
}

.attachments h4 {
  margin-bottom: 8px;
  color: #2c3e50;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 6px;
}

.file-size {
  font-size: 12px;
  color: #909399;
}

.message-actions {
  display: flex;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.related-messages {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.related-messages h4 {
  margin-bottom: 12px;
  color: #2c3e50;
}

.related-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.related-item {
  padding: 12px;
  background: #f5f7fa;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.related-item:hover {
  background: #e6f7ff;
}

.related-title {
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.related-time {
  font-size: 12px;
  color: #909399;
}
</style>
